from rest_framework.decorators import api_view
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, \
    DestroyModelMixin
from rest_framework.viewsets import GenericViewSet

from apps.models import User
from apps.serializers.UserSerializer import UserSerializer
from apps.utils.common_mixin import APIListModelMixin, APICreateModelMixin
from apps.utils.common_response import APIResponse
from apps.views.main.user import make_login_log


class AdminInfoListView(GenericViewSet):
    def list(self, request):
        keyword = request.GET.get("keyword", None)
        if keyword:
            user_data = User.objects.filter(username__contains=keyword).order_by(
                '-create_time')
        else:
            user_data = User.objects.all().filter().order_by('-create_time')
        serializer = UserSerializer(user_data, many=True)
        return APIResponse(msg='查询成功', data=serializer.data)


class AdminInfoCreateView(GenericViewSet, APICreateModelMixin):
    queryset = User.objects.all()
    serializer_class = UserSerializer


class AdminInfoUpdateView(GenericViewSet):
    def create(self, request):
        try:
            id = request.GET.get('id')
            # 编辑更新
            # HouseKeeping_data=HouseKeeping.objects.get(pk=id)
            user_data = User.objects.filter(id=id).first()
        except User.DoesNotExist:
            make_login_log(request)
            return APIResponse(code=1, msg='对象不存在')
        serializer = UserSerializer(user_data, data=request.data)
        if serializer.is_valid():
            serializer.save()
        return APIResponse(code=0, msg='更新成功', data=serializer.data)


class AdminInfoDeleteView(GenericViewSet):
    def create(self, request):
        try:
            ids = request.GET.get('ids')
            ids_arr = ids.split(',')
            # 批量删除
            User.objects.filter(id__in=ids_arr).delete()
        except User.DoesNotExist:
            make_login_log(request)
            return APIResponse(code=1, msg='对象不存在')
        return APIResponse(code=0, msg='删除成功')


# 按关键字搜索
